<?php

namespace App\Remote\Tiger;

use App\Kuafu\User\Service\AuthService;
use Closure;
use Illuminate\Support\Facades\Cache;

class Remote extends \App\Remote\Remote
{
    const CACHE_TIME = 300;

    /**
     * @inheritDoc
     */
    static function getBaseUri(): string
    {
        // TODO: Implement getBaseUri() method.
        return config('InternalAPI.domain.tiger');
    }

    public static function registerResponseHandle(): Closure
    {
        return function (string $data) {
            $response = json_decode($data, true);
            if ($response["code"] != 200) {
                throw new \Exception(vsprintf("响应数据异常 code: [%s] msg: [%s]", [
                    $response["code"],
                    $response["msg"]
                ]));
            }
            return $response["data"];
        };
    }


    /**
     * @param Closure $closure
     * @param string $cacheKey
     * @param int $ttl
     * @return mixed
     */
    public static function cached(Closure $closure, string $cacheKey, int $ttl = self::CACHE_TIME)
    {
        return Cache::store("redis")->remember($cacheKey, $ttl, $closure);
    }

    public static function buildBasicHeaders(): array
    {
        try {
            $userId   = AuthService::getUserId();
            $username = AuthService::getAuthUser()['username'];
        } catch (\Exception $exception) {
            $userId   = 1;
            $username = '系统';
        }

        return [
            'internal-key'   => 'rms',
            'internal-token' => config('InternalAPI.tokens.rms'),
            'userId'         => $userId,
            'username'       => $username,
            'Content-Type'   => 'application/json'
        ];
    }
}
